#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
struct DSU {
    vector<int> parent, size;
    DSU(int n) {
        parent.resize(n + 1);
        size.resize(n + 1, 1);
        for(int i = 1; i <= n; i++) {
            parent[i] = i;
        }
    }
    int find(int x) {
        if(parent[x] != x) {
            return parent[x] = find(parent[x]);
        }
        return parent[x];
    }
    void unite(int x, int y) {
        int fx = find(x), fy = find(y);
        if(fx == fy) {
            return;
        }
        parent[fy] = fx;
        size[fx] += size[fy];
    }
    bool same(int x, int y) {
        return find(x) == find(y);
    }
};
int main() {
    string t;
    unordered_map<string, int> h;
    unordered_map<int, string> p;
    DSU a(50020);
    int k = 1;
    while(1) {
        string s;
        cin >> s;
        if(s == "$") {
            break;
        }
        string temp(s.begin() + 1, s.end());
        if(!h[temp]) {
            h[temp] = k;
            p[k] = temp;
            k++;
        }
        if(s[0] == '#') {
            t = temp;
        }else if(s[0] == '+'){
            a.unite(h[t], h[temp] );
        }else {
            int q = a.find(h[temp]);
            cout << temp << " " << p[q] << endl;
        }
    }

    return 0;
}